<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import YzmBtn from '@/components/YzmBtn.vue'
import { ShoppingCartOutlined } from '@ant-design/icons-vue'
import { validEmail, validPwd } from '@/utils/valid'
import { useCartStore, useCommonStore, useUserStore } from '@/stores'
import {
  getConfirmOrderPageApi,
  getGiftsGoodsApi,
  submitOrderApi,
  integralPayApi,
  registerApi,
} from '@/api'
import Button from '@/components/Button.vue'
import { message } from 'ant-design-vue'

const router = useRouter()
const route = useRoute()
const submitRef = ref()
const token = computed(() => useUserStore().token)
const cartInfo = computed(() => useCartStore().cartInfo)
const fromData = ref({
  email: '',
  use_integral: 0, // 是否用金币抵扣1是0否
  pay_type: 'paypal',
  account: '',
  first_name: '',
  last_name: '',
  platform: null,
  discount_code: '',
  note: '',
  loginpass: '',
  code: '',
})
const giftList = ref([])
const selectedGift = ref([])
const sku_details = computed(() => {
  const list = []
  cartInfo.value.list.forEach((item) => {
    list.push({
      goods_item_id: item.sku_id || item.shop_goods_item_id,
      num: item.num,
      is_gifts: 0,
    })
  })
  return list
})
const rules = {
  email: [{ validator: validEmail, trigger: 'blur' }],
  loginpass: [{ validator: validPwd, trigger: 'blur' }],
  code: [{ required: true, message: 'Please enter your verification code', trigger: 'blur' }],
  first_name: [{ required: true, message: 'Please enter your first name', trigger: 'blur' }],
  last_name: [{ required: true, message: 'Please enter your last name', trigger: 'blur' }],
  platform: [{ required: true, message: 'Please select your platform', trigger: 'change' }],
  account: [{ required: true, message: 'Please enter your console user id', trigger: 'blur' }],
}
const checked = ref(false)
const goBack = () => {
  router.back()
}
// 获取订单页面信息
const getConfirmPageInfo = () => {
  const { selectedGame, selectedArea } = useCommonStore()
  const params = {
    game_id: selectedGame.key,
    area_id: selectedArea.key,
    use_integral: fromData.value.use_integral,
    pay_type: fromData.value.pay_type,
    sku_details: sku_details.value,
  }
  getConfirmOrderPageApi(params).then((res) => {
    getGiftList({
      game_id: selectedGame.key,
      area_id: selectedArea.key,
      order_total: res.pay_amount,
    })
  })
}
// 获得赠品列表
const getGiftList = (params) => {
  getGiftsGoodsApi(params).then((res) => {
    if (res.length) {
      res.forEach((item) => {
        item.selected = null
      })
    }
    giftList.value = res
  })
}
const changeGift = (index, id) => {
  selectedGift.value[index] = { goods_item_id: id, num: 1, is_gifts: 1 }
}
// 提交订单
const submitOrder = () => {
  const { loginpass, ...newData } = fromData.value
  const { selectedGame, selectedArea } = useCommonStore()
  const params = {
    ...newData,
    game_id: selectedGame.key,
    area_id: selectedArea.key,
    sku_details: [...sku_details.value, ...selectedGift.value],
  }
  submitRef.value.validate().then(() => {
    submitOrderApi(params).then((res) => {
      // 金币支付
      if (fromData.value.pay_type === 'integral') {
        integralPay(res)
      } else {
        // paypal 支付
        // 去PayPal扥支付页请求支付
        message.info('PayPal payment is not supported at the moment')
      }
      if (checked.value) register()
    })
  })
}
// 积分支付
const integralPay = (pay) => {
  const { getUserInfo } = useUserStore()
  const payParam = {
    pay_type: 'integral',
    target: pay.trade_sn,
    target_type: 'orderall',
    pay: [
      {
        pay_type: 'integral',
        money: pay.total_amount,
      },
    ],
  }
  integralPayApi(payParam).then(() => {
    router.back()
    getUserInfo()
    message.success('Payment successful')
  })
}
// 注册
const register = () => {
  const { email, code, loginpass, last_name, first_name } = fromData.value
  registerApi({
    email,
    code,
    loginpass,
    last_name,
    first_name,
  }).then(() => {
    message.success('Registration successful')
  })
}
onMounted(() => {
  const { code } = route.query
  fromData.value.discount_code = code
  getConfirmPageInfo()
})
</script>
<template>
  <div class="bg-gray-50 w-full">
    <div class="max-w-[1200px] mx-auto p-3 bg-white">
      <!-- 顶部 -->
      <div class="flex justify-evenly items-center border-b border-gray-200 pb-5">
        <span> </span>
        <img src="@/assets/icons/logo.webp" class="h-8" alt="" />
        <div class="cursor-pointer" @click="goBack">
          <ShoppingCartOutlined />
        </div>
      </div>
      <div class="flex flex-row-reverse max-[750px]:block">
        <!-- 商品信息 -->
        <div class="flex-1 p-5 flex flex-col gap-5">
          <div
            class="flex flex-col gap-4 max-h-80 overflow-y-auto max-w-[70%] max-[750px]:max-w-full"
          >
            <div
              class="flex justify-between items-center p-3 border border-[#ccc]"
              v-for="item in cartInfo.list"
              :key="item"
            >
              <div class="flex gap-2">
                <img :src="item.img" class="size-10 object-cover" alt="" />
                <div>
                  <div>{{ item.name }}</div>
                  <div class="text-xs text-[#ccc]">
                    {{ item.sku_title || item.spece_value_title }}
                  </div>
                </div>
              </div>
              <div class="flex gap-2">
                <div>${{ item.price }}</div>
                <div>x{{ item.num }}</div>
              </div>
            </div>
          </div>
          <div class="text-xl flex justify-between items-center max-w-[70%] max-[750px]:max-w-full">
            <span class="font-bold">ALL</span>
            <span>usd ${{ cartInfo.total }}</span>
          </div>
          <div class="flex flex-col gap-5 max-w-[70%] max-[750px]:max-w-full">
            <!-- 支付方式 -->
            <div class="flex flex-col gap-3" v-if="token">
              <div>Payment Method</div>
              <a-radio-group v-model:value="fromData.pay_type" button-style="solid">
                <a-radio-button value="paypal">PayPal</a-radio-button>
                <a-radio-button value="integral">Integral</a-radio-button>
              </a-radio-group>
            </div>
            <!-- 提交订单 -->
            <div class="pt-5 w-full">
              <Button class="w-full" @click="submitOrder"> Submit Order </Button>
            </div>
          </div>
        </div>
        <!-- 下单信息 -->
        <div class="flex-1 p-5 border-r border-gray-200 max-[750px]:border-0">
          <div class="font-bold text-2xl mb-5">Customer details</div>
          <a-form ref="submitRef" :model="fromData" :rules="rules" autocomplete="off">
            <a-form-item name="email">
              <div class="flex flex-col gap-3">
                <label class="text-gray-500">Email address</label>
                <a-input
                  type="email"
                  v-model:value="fromData.email"
                  placeholder="Please enter your email address"
                  :bordered="false"
                />
              </div>
            </a-form-item>
            <div class="flex gap-5">
              <a-form-item name="first_name" class="flex-1">
                <div class="flex flex-col gap-3">
                  <label class="text-gray-500">First name</label>
                  <div class="bg-gray">
                    <a-input
                      v-model:value="fromData.first_name"
                      placeholder="Please enter your first name"
                      :bordered="false"
                    />
                  </div>
                </div>
              </a-form-item>
              <a-form-item name="last_name" class="flex-1">
                <div class="flex flex-col gap-3">
                  <label class="text-gray-500">Last name</label>
                  <div class="bg-gray">
                    <a-input
                      v-model:value="fromData.last_name"
                      placeholder="Please enter your last name"
                      :bordered="false"
                    />
                  </div>
                </div>
              </a-form-item>
            </div>
            <a-form-item name="platform">
              <div class="flex flex-col gap-3">
                <label class="text-gray-500">Platform</label>
                <div class="bg-gray">
                  <a-select
                    v-model:value="fromData.platform"
                    placeholder="Please select your platform"
                    :bordered="false"
                  >
                    <a-select-option value="Switch">Switch</a-select-option>
                    <a-select-option value="Xbox">Xbox</a-select-option>
                    <a-select-option value="PS4">PS4/5</a-select-option>
                  </a-select>
                </div>
              </div>
            </a-form-item>
            <a-form-item name="account">
              <div class="flex flex-col gap-3">
                <label class="text-gray-500">Console User ID</label>
                <div class="bg-gray">
                  <a-input
                    v-model:value="fromData.account"
                    :bordered="false"
                    placeholder="Enter your console user ID for face to face delivery"
                  />
                </div>
              </div>
            </a-form-item>
            <!-- 是否创建账户 -->
            <div class="mb-3" v-if="!token">
              <a-checkbox v-model:checked="checked">Create an account?</a-checkbox>
            </div>
            <a-form-item name="loginpass" v-if="checked">
              <div class="flex flex-col gap-3">
                <label class="text-gray-500">Create account password </label>
                <div class="bg-gray">
                  <a-input
                    v-model:value="fromData.loginpass"
                    :bordered="false"
                    placeholder="Enter your password"
                  />
                </div>
              </div>
            </a-form-item>
            <a-form-item name="code" v-if="checked">
              <div class="flex flex-col gap-3">
                <label class="text-gray-500">Verification code </label>
                <div class="bg-gray flex gap-3">
                  <a-input
                    v-model:value="fromData.code"
                    :bordered="false"
                    placeholder="Enter your verification code"
                  />
                  <YzmBtn :email="fromData.email" :type="1" />
                </div>
              </div>
            </a-form-item>
            <div class="text-xl font-bold">Additional Information</div>
            <a-form-item>
              <div class="flex flex-col gap-3">
                <label class="text-gray-500">Order notes(optional)</label>
                <div class="bg-gray">
                  <textarea
                    class="textarea"
                    v-model="fromData.note"
                    placeholder="Notes about your, e.g. special notes for delivery"
                  />
                </div>
              </div>
            </a-form-item>
            <div v-if="giftList.length">
              <div class="text-xl font-bold mt-5">Take Your Gifts</div>
              <div>
                <div class="flex justify-between items-center font-bold border-b border-[#ccc]">
                  <span class="p-5 pb-2 min-w-[100px]"> Gift For </span>
                  <span class="flex-1 text-center"> Product </span>
                </div>
                <div
                  class="flex justify-between items-center"
                  v-for="(item, index) in giftList"
                  :key="item.level"
                >
                  <span class="p-5 min-w-[100px] text-center"> ${{ item.level }} </span>
                  <a-select
                    class="flex-1"
                    v-model:value="item.selected"
                    placeholder="Please select gift"
                    :bordered="false"
                    @change="changeGift(index, $event)"
                  >
                    <a-select-option :value="gift.id" v-for="gift in item.child">
                      {{ gift.goods_name }}
                    </a-select-option>
                  </a-select>
                </div>
              </div>
            </div>
          </a-form>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.ant-input,
.ant-select,
.textarea {
  line-height: 28px;
  border-radius: 0 !important;
  background-color: #f5f5f5;
  border: 1px solid #ccc !important;
}
.textarea {
  outline: none;
  width: 100%;
  min-height: 120px;
  padding: 10px 12px;
}
.ant-radio-group {
  height: 40px !important;
  display: flex !important;
}
:deep(.ant-radio-button-wrapper) {
  height: 100%;
  font-size: 16px;
  line-height: 38px;
  flex: 1 !important;
}
</style>
